<?php
declare (strict_types=1);

namespace app\controller\admin;

use app\common\service\redis\PoolRedis;
use app\model\AdminOption;
use app\util\ReturnCode;
use think\Response;

class Index extends Base {

    public function upload(): Response {
        $path = '/upload/' . date('Ymd', time()) . '/';
        $name = $_FILES['file']['name'];
        $tmp_name = $_FILES['file']['tmp_name'];
        $error = $_FILES['file']['error'];
        //过滤错误
        if ($error) {
            switch ($error) {
                case 1:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中UPLOAD_MAX-FILESIZE的大小';
                    break;
                case 2:
                    $error_message = '您上传的文件超过了PHP.INI配置文件中的post_max_size的大小';
                    break;
                case 3:
                    $error_message = '文件只被部分上传';
                    break;
                case 4:
                    $error_message = '文件不能为空';
                    break;
                default:
                    $error_message = '未知错误';
            }
            die($error_message);
        }
        $arr_name = explode('.', $name);
        $hz = array_pop($arr_name);
        $new_name = md5(time() . uniqid()) . '.' . $hz;
        if (!file_exists($_SERVER['DOCUMENT_ROOT'] . $path)) {
            mkdir($_SERVER['DOCUMENT_ROOT'] . $path, 0755, true);
        }
        if (move_uploaded_file($tmp_name, $_SERVER['DOCUMENT_ROOT'] . $path . $new_name)) {
            return $this->buildSuccess([
                'fileName' => $new_name,
                'fileUrl'  => $this->request->domain() . $path . $new_name
            ]);
        } else {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, '文件上传失败');
        }
    }

    public function getSetting(): Response  {
        $setting = (new AdminOption())->where('group', 'default')
            ->whereIn('name', "sitename,service_phone")
            ->column('value', 'name');
        return $this->buildSuccess([
            'setting'  => $setting,
        ]);
    }

    public function setting(): Response  {
        $sitename = $this->request->post('sitename/s');
        $service_phone = $this->request->post('service_phone/s');
        $op = AdminOption::where('name', 'sitename')->where('group', 'default')->find();
        if (!$op) {
            $op = new AdminOption();
            $op->group = 'default';
            $op->name = 'sitename';
        }
        $op->value = $sitename;
        $op->save();
        $res = AdminOption::where('name', 'service_phone')->where('group', 'default')->find();
        if (!$res) {
            $res = new AdminOption();
            $res->group = 'default';
            $res->name = 'service_phone';
        }
        $res->value = $service_phone;
        $res->save();
        return $this->buildSuccess();
    }

    /**
     * @func template
     * @desc 导出上传模板文件
     * @return \think\Response
     * @Time: 2021/9/23 11:18
     */
    public function exportTemplate(): Response  {
        $path = $this->request->domain().'/template/';
        $type = $this->request->get('type');
        if ($type) {
            return $this->buildSuccess([
                'fileUrl'  => $path . $type . "_temp.xlsx"
            ]);
        }
        return $this->buildFailed(ReturnCode::NOT_EXISTS);
    }

    /**
     * @notes: 返回上传错误信息
     * @return Response
     * @author: speed
     */
    public function getUploadResult(): Response  {
        $type = $this->request->get('type');
        $redis = PoolRedis::instance();
        $list = [];
        while ($datum = $redis->rPop("upload_{$type}_error")) {
            $list[] = unserialize($datum);
        }
        $newList = [
            'error' => [],
            'number' => []
        ];
        foreach ($list as $item) {
            if (in_array($item['error_msg'], $newList['error'])) {
                $key = array_search($item['error_msg'], $newList['error']);
                $newList['number'][$key][] = $item['data']['number'];
            } else {
                $newList['error'][] = $item['error_msg'];
                $newList['number'][] = [$item['data']['number']];
            }
        }
        return $this->buildSuccess([
            'list'  => $newList
        ]);
    }
}
